const express = require('express')
const {
  check
} = require('express-validator')
const {
  validate
} = require('../utils/validate')

const controller = require('../controllers/book')

const router = express.Router()

const {
  uploadBook
} = require('../utils/upload')

router.route('/books')
  .post(
    uploadBook.single('book'),
    controller.create)
  .get(
    validate([
      check('feature').optional().isString().withMessage('feature 必须是字符串类型'),
      check('category').optional().isString().withMessage('category 必须是字符串类型'),
      check('search').optional().isString().withMessage('search 必须是字符串类型'),
      check('page').optional().isInt().withMessage('page 必须是数值类型'),
      check('pagesize').optional().isInt().withMessage('pagesize 必须是数值类型'),
      // check().custom(body => {
      //   console.log(Object.keys(body))
      //   const keys = ['feature', 'category', 'search', 'page', 'pagesize']
      //   return Object.keys(body).every(key => keys.includes(key))
      // }).withMessage('参数只能包含feature, category, search, page, pagesize')
    ]),
    controller.index)

router.route('/books/:id')
  .get(controller.show)
  .put(
    validate([
      check('title').optional().isString().withMessage('title 必须是字符串类型'),
      check('author').optional().isString().withMessage('author 必须是字符串类型'),
      check('category').optional().isString().withMessage('category 必须是字符串类型'),
      check('description').optional().isString().withMessage('description 必须是字符串类型'),
      check('rank').optional().isInt().withMessage('rank 必须是数值类型'),
      check().custom(body => {
        const keys = ['title', 'author', 'category', 'description', 'rank']
        return Object.keys(body).every(key => keys.includes(key))
      }).withMessage('参数只能包含title, author, category, description, rank')
    ]),
    controller.update)
  .delete(controller.delete)

module.exports = router
